package com.yingxin.yxerp.module.permission.vo.req.helper;

import cn.hutool.core.collection.CollectionUtil;
import com.yingxin.yx.framework.user.dto.AppPermissionDto;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class AppPermissionManagerTreeHelper {

    public static List<AppPermissionDto> build(List<AppPermissionDto> permissions) {
        List<AppPermissionDto> tree = new ArrayList<>();
        for (AppPermissionDto permission : permissions) {
            String ROOT_ID = "0";
            if (ROOT_ID.equals(permission.getParentId())) {
                findChild(permission, permissions);
                tree.add(permission);
            }
        }
        CollectionUtil.sort(tree, Comparator.comparingInt(AppPermissionDto::getSort));
        return tree;
    }

    /**
     * 递归查找子级
     *
     * @param parent
     * @param permissions
     */
    private static void findChild(AppPermissionDto parent, List<AppPermissionDto> permissions) {
        for (AppPermissionDto permission : permissions) {
            if (null != permission.getParentId() && permission.getParentId().equals(parent.getId())) {
                findChild(permission, permissions);
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(permission);
            }
        }
    }
}
